// pages/shipin-comment/shipin-comment.js
import formatTime from '../../../../style/formatTime'
const db = wx.cloud.database()
const _ = db.command
let userInfo = {}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    shipin: {},
    commentList: [],
    shipinId: '',
    dianzan: '',
    // 登录组件是否显示
    loginShow: false,
    // 底部弹出层是否显示
    modalShow: false,
    modalShow1: false,
    id: '',
    openidfb: '',
    openidsd: '',
    isOpen: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    console.log(options)
    this.setData({
      shipinId: options.shipinId
    })

    wx.cloud.callFunction({
      name: 'getOpenid',
      complete: res => {
        this.setData({
          openid: res.result.openid
        })
        var openid = res.result.openid
        db.collection('dianzan').where({
          _id: options.shipinId + openid,
        })
          .get().then((res) => {
            if (res.data == '') {
              this.setData({
                dianzan: false,
                dianzanUrl: "/images/dianzan_2.png"
              })
            } else {
              this.setData({
                dianzan: res.data[0].dianzan,
                dianzanUrl: "/images/dianzan_1.png"
              })
            }

          })

      }
    })
    this._getsc()
    this._getshipinDetail()
  },
  jvbao(event){
    wx.navigateTo({
      url: '/pages/index/jvbao/jvbao?tieziid=' + this.data.shipin._id +'&ip=' + this.data.shipin.ip +'&openid='+this.data.shipin._openid+'&nr='+ event.currentTarget.dataset.nr +'&id='+66,
    })
    this.setData({
      modalShow1: false,
    })
  },
  // 获取内容
  _getshipinDetail() {
    wx.cloud.callFunction({
      name: 'shipin',
      data: {
        shipinId: this.data.shipinId,
        $url: 'detail',
      }
    }).then((res) => {
      let commentList = res.result.commentList.data
      for (let i = 0, len = commentList.length; i < len; i++) {
        commentList[i].createTime = formatTime(new Date(commentList[i].createTime))
        for (let g = 0, len = commentList[i].reply_list.length; g < len; g++) {
          commentList[i].reply_list[g].createTime = formatTime(new Date(commentList[i].reply_list[g].createTime))
        }
      }
      this.setData({
        commentList,
        shipin: res.result.detail[0],
        len: commentList.length
      })
      console.log(res)
    })
  },


  // 点击收藏按钮
  _getsc() {
    db.collection('shouchang').where({
      shipinId: this.data.shipinId,
    })
      .get().then((res) => {
        this.setData({
          sc: res.data.length,
        })
        this._getscurl()
      })
  },
  // 收藏图片改变
  _getscurl() {

    db.collection('shouchang').where({
      _id: this.data.shipinId + this.data.openid,
    })
      .get().then((res) => {
        if (res.data == '') {
          this.setData({
            scUrl: "/images/wodeshoucang.png"
          })
        } else {
          this.setData({
            scUrl: ""
          })
        }
      })
  },
  // 收藏功能
  onTapTosc: function () {
    wx.showLoading({
      title: '收藏中',
      mask: true,
    })
    db.collection('shouchang').add({
      data: {
        _id: this.data.shipinId + this.data.openid,
        content: this.data.shipin.content,
        createTime: db.serverDate(),
        shipinId: this.data.shipinId,
        nickName: this.data.shipin.nickName,
        avatarUrl: this.data.shipin.avatarUrl,
        video: this.data.shipin.video,
        ip: 333
      }
    }).then((res) => {   
      wx.showToast({
        title: '收藏成功',
      })
      wx.hideLoading()

      this.setData({
        scUrl: ""
      })
      this._getshipinDetail()
      this._getsc()
    }).catch((err) => {
      wx.hideLoading()
    })

  },
  onComment() {
    // 判断用户是否授权
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: (res) => {
              userInfo = res.userInfo
              // 显示评论弹出层
              this.setData({
                modalShow: true,
              })
            }
          })
        } else {
          this.setData({
            loginShow: true,
          })
        }
      }
    })
  },

  onLoginsuccess(event) {
    userInfo = event.detail
    // 授权框消失，评论框显示
    this.setData({
      loginShow: false,
    }, () => {
      this.setData({
        modalShow: true,
      })
    })
  },

  onLoginfail() {
    wx.showModal({
      title: '授权用户才能进行评价',
      content: '',
    })
  },
  onSend(event) {
    // console.log(this.data.shipin.opid)
    // console.log(event)
    // 插入数据库
    let content = event.detail.value.content
    if (content.trim() == '') {
      wx.showModal({
        title: '评论内容不能为空',
        content: '',
      })
      return
    }
    wx.showLoading({
      title: '评论中',
      mask: true,
    })
    db.collection('meitu-pl').add({
      data: {
        content,
        createTime: db.serverDate(),
        shipinId: this.data.shipin._id,
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        ip: 400,
        biaoqian_ming: this.data.shipin.biaoqian_ming,
        openidsd: this.data.shipin.opid,
        isOpen: false,
        reply_list: [],
      }
    }).then((res) => {
      wx.hideLoading()
      wx.showToast({
        title: '评论成功',
      })
      this.setData({
        modalShow: false,
        content: '',
      })
      this._getshipinDetail()
    })
  },
  // 点击展开
  chooseUnfold: function (e) {
    var key = e.currentTarget.dataset.key;
    var val = e.currentTarget.dataset.value;
    key = key + '.isOpen';
    this.setData({
      [key]: !val
    })
  },
  onLoginsuccess1(event) {
    userInfo = event.detail
    // 授权框消失，评论框显示
    this.setData({
      loginShow: false,
    }, () => {
      this.setData({
        modalShow1: true,
      })
    })
  },
  onComment1(event) {
    // 判断用户是否授权
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: (res) => {
              userInfo = res.userInfo
              // 显示评论弹出层
              this.setData({
                modalShow1: true,
                id: event.currentTarget.dataset.id,
                mz: event.currentTarget.dataset.mz,
                openidsd: event.currentTarget.dataset.openidsd,
              })
            }
          })
        } else {
          this.setData({
            loginShow: true,
          })
        }
      }
    })
  },
  onSend1(event) {
    let content = event.detail.value.content;
    let createTime = db.serverDate();
    let nickName = userInfo.nickName;
    let openidfb = this.data.openid;
    let openidsd = this.data.openidsd;
    let mz = this.data.mz;
    if (content.trim() == '') {
      wx.showModal({
        title: '回复内容不能为空',
        content: '',
      })
      return
    }
    wx.showLoading({
      title: '回复中',
      mask: true,
    })
    db.collection('meitu-pl').where({
      _id: this.data.id
    }).update({
      data: {
        reply_list: _.push({
          openidfb: openidfb,
          openidsd: openidsd,
          content: content,
          createTime: createTime,
          nickName: nickName,
          avatarUrl: userInfo.avatarUrl,
          mz: mz,
          biaoqian_ming: this.data.shipin.biaoqian_ming,
          tieziId: this.data.shipinId
        }),
      }
    }).then((res) => {
      wx.hideLoading()
      wx.showToast({
        title: '回复成功',
      })
      this.setData({
        modalShow1: false,
        content: '',
        id: '',
        mz: '',
      })
      this._getshipinDetail()
    })

  },
  /**
* 点赞功能
*/
  clickMe: async function () {
    wx.showLoading({
      title: '点赞中...',
    })

    var dianzan1 = this.data.dianzan
    //云函数方式操作

    if (this.data.dianzan == true) {
      wx.cloud.callFunction({
        name: 'dianzan',
        data: {
          dianzan: dianzan1,
          id: this.data.shipin._id,
          ip: 400,
          $url: 'delzan'
        }
      }).then((res) => {
        // console.log(res.result)
        this.setData({
          dianzanUrl: "/images/dianzan_2.png",
          dianzan: !dianzan1,
        })
        wx.showToast({
          title: '点赞取消',
          icon: 'success',
          duration: 1500
        })
      })
      this._getshipinDetail()
    } else {
      wx.cloud.callFunction({
        name: 'dianzan',
        data: {
          dianzan: !dianzan1,
          id: this.data.shipin._id,
          ip: 400,
          $url: 'addzan'
        }
      }).then((res) => {
        // console.log(res.result)
        this.setData({
          dianzanUrl: "/images/dianzan_1.png",
          dianzan: !dianzan1
        })
        wx.showToast({
          title: '点赞成功',
          icon: 'success',
          duration: 1500
        })
        this._getshipinDetail()
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const shipin = this.data.shipin
    return {
      title: shipin.content,
      path: `/pages/shipin-nr/shipin-nr?shipinId=${shipin._id}`,

    }
  }
})